<?php

namespace App\Dao;


use App\Constants\CodeData;
use App\Model\Photo;
use App\Utils\FunUtil;
use App\Utils\MemcacheClient;
use Hyperf\Context\ApplicationContext;
use Hyperf\DbConnection\Db;

class PhotoDao
{
    private static $instance;

    public static function getInstance()
    {
        if (!self::$instance) {
            self::$instance = Applicationcontext::getcontainer()->get(self::class);
        }
        return self::$instance;
    }


    //获取免费相片 前5张
    public function getList($userId)
    {
        $list = MemcacheClient::getInstance()->get("user_photo_one_list_" . $userId);
        if ($list === false) {
            $list = Photo::query()
                ->where('uid', $userId)->where('status', 3)->where('is_recommend', 0)
                ->orderBy('ctime', 'desc')
                ->limit(5)->get()->toArray();
            if (!empty($list)) {
                foreach ($list as $k => $v) {
                    $list[$k]['path'] = FunUtil::formatPhoto($v['path']);
                    $list[$k]['thumb'] = FunUtil::formatPhoto($v['thumb']);
                }
            }
            MemcacheClient::getInstance()->set("user_photo_one_list_" . $userId, $list, 300);
        }

        return $list;
    }


    /**
     * Note - 获取用户的相片列表、获取审核通过他人相片
     * DateTime 2024/7/16 17:56
     * User Admin
     * @param $uid
     * @param $type
     * @param $page
     * @param $pageSize
     * @param $from
     * @param $version_code
     * @param $channel
     * @return array
     */
    public function getUserPhotos($uid, $type, $page, $pageSize, $from, $version_code, $channel)
    {
        $where = [];
        if ($type == 1) {
            $where[] = ['uid', '=', $uid];
        } else {
            if ((new AppUpgradeDao())->isHideCall($from, $version_code, $channel)) {
                $where[] = ['status', '=', 3];
                $where[] = ['uid', '=', $uid];
                $where[] = ['is_recommend', '=', 0];
            } else {
                $where[] = ['status', '=', 3];
                $where[] = ['uid', '=', $uid];
            }
        }

        $list = Photo::select(['id', 'uid', 'path', 'thumb', 'is_recommend'])->where($where)
            ->orderBy('is_recommend', 'desc')->orderBy('ctime', 'desc')->forPage($page, $pageSize)->get()->toArray();

        if (!empty($list)) {
            foreach ($list as $k => $v) {
                $list[$k]['path'] = FunUtil::formatPhoto($v['path']);
                $list[$k]['thumb'] = FunUtil::formatPhoto($v['thumb']);
            }
        }
        return $list;
    }


    public function getFemalePhotoPath($uid, $isRecommend = 0)
    {
        // $sql = "SELECT p.path from tb_photos p WHERE p.uid = ? AND p.is_recommend = ? AND p.status = ? ORDER BY RAND() LIMIT 1";
        // $pd = $this->createCommand($sql);
        // $pd->execute([$uid, $isRecommend, 3]);
        // $rs = $pd->fetch(PDO::FETCH_ASSOC);
        $rs = Photo::query()->where('id', $uid)->where('is_recommend', $isRecommend)->where('status', 3)->inRandomOrder()->first();
        $rs = modelToArray($rs);
        return $rs['path'] ?? '';
    }


    /**
     * Note - 用户上传的照片数量
     * DateTime 2024/8/9 15:54
     * User Admin
     * @param $uids
     * @param int $status - 1：待审核，2：审核不通过，3：审核通过
     * @return false|int|mixed
     */
    public function getUserPhotoNum($uids, int $status = 3)
    {
        if (is_array($uids)) {
            if (empty($uids)) {
                return false;
            }
            $rs = Photo::query()
                ->whereIn('uid', $uids)
                ->where('status', 3)
                ->groupBy('uid')
                ->select('uid', DB::raw('COUNT(*) AS total'))
                ->get()
                ->keyBy('uid')
                ->pluck('total');
            return $rs->toArray();
        } else {
            $uid = $uids;
            $total = MemcacheClient::getInstance()->get("user_photo_num_" . $uid . "_" . $status);
            if ($total === false) {
                $query = Photo::query()->where('uid', $uid);
                if ($status > 0) {
                    $query->where('status', $status);
                } else {
                    $query->where('status', '<>', 2); // Use '<>' for '!='
                }
                $total = $query->count();
                MemcacheClient::getInstance()->set("user_photo_num_" . $uid . "_" . $status, $total, 300);
            }
            return $total;
        }

    }


    /**
     * Note - 上传照片
     * DateTime 2024/8/9 15:51
     * User Admin
     * @param $uid
     * @param $vip
     * @param $is_recommend
     * @param $image_url
     * @return array
     */
    public function insert($uid, $vip, $is_recommend, $image_url)
    {
        $num_limit = $vip == 1 ? 30 : 3;
        $all_num = $this->getUserPhotoNum($uid, 0);
        if ($all_num >= $num_limit) {
            // Tool::JSON(\CodeData::NEED_TIPS, '', '你上传的图片已达到上限');
            return formatData('', 200, CodeData::NEED_TIPS, '你上传的图片已达到上限');
        }
        $data = array();
        $data['uid'] = $uid;
        $data['name'] = time();
        $data['path'] = $image_url;
        $data['thumb'] = $image_url;
        $data['is_recommend'] = $is_recommend;
        $data['ctime'] = time();
        $data['hash'] = time();
        $data['status'] = 1; //

        //插入成功后返回id
        $photo_id = Photo::query()->insertGetId($data);
        $memcache = MemcacheClient::getInstance();
        if ($photo_id) {
            $memcache->delete("user_photo_one_list_" . $uid);
            $memcache->delete("user_photo_list_" . $uid);
            $memcache->delete('user_photo_' . $uid);
            $memcache->delete("user_photo_num_" . $uid . "_0");
            //审核通过后才算完全任务
            //MissionMgr::uploadAlbum($uid, $userInfo['sex']);
            // 上传照片记录主播排序分
            // AnchorSortLogModel::record($uid,6,1);
            //成功返回照片id和图片地址path
            $retval = array('result' => 1, 'msg' => array('id' => $photo_id, 'thumb' => $image_url, 'path' => $image_url));
            // Tool::JSON(\CodeData::SUCCESS, $retval, '上传成功');
            return formatData($retval, 200, CodeData::SUCCESS, '操作成功');
        } else {
            // Tool::JSON(\CodeData::NEED_TIPS, '', '上传失败');
            return formatData('', 200, CodeData::NEED_TIPS, '上传失败');
        }
    }


    /**
     * Note - 修改照片
     * DateTime 2024/8/9 16:05
     * User Admin
     * @param $uid
     * @param $id
     * @param $is_recommend
     * @return array
     */
    public function update($uid, $id, $is_recommend)
    {
        $res = Photo::query()->where('uid', $uid)->whereIn('id', $id)->update(["is_recommend" => $is_recommend]);
        if ($res) {
            $memcache = MemcacheClient::getInstance();
            $memcache->delete("user_photo_one_list_" . $uid);
            $memcache->delete("user_photo_list_" . $uid);
            $memcache->delete('user_photo_' . $uid);
            $memcache->delete("user_photo_num_" . $uid . "_0");
            //成功返回照片id和图片地址path
            $retval = array('result' => 1, 'msg' => array('id' => $id));
            return formatData($retval, 200, CodeData::SUCCESS);
        } else {
            return formatData('', 200, CodeData::NEED_TIPS, '修改失败');
        }

    }


    /**
     * Note - 删除照片
     * DateTime 2024/8/9 16:11
     * User Admin
     * @param $uid
     * @param $id
     * @return array
     */
    public function delete($uid, $id)
    {
        $id = array_filter($id);
        if (empty($id)) {
            return formatData('', 200, CodeData::NEED_TIPS, '相片不存在');
        }
        $ret = Photo::query()->where('uid', $uid)->whereIn('id', $id)->delete();
        if ($ret) {
            //删除缓存，本来是重新设置缓存值得，现在改成直接删除了
            $memcache = MemcacheClient::getInstance();
            $memcache->delete("user_photo_one_list_" . $uid);
            $memcache->delete("user_photo_list_" . $uid);
            $memcache->delete('user_photo_' . $uid);
            $memcache->delete("user_photo_num_" . $uid . "_0");
            return formatData(['result' => $ret], 200, CodeData::SUCCESS);
        } else {
            // Tool::JSON(\CodeData::NEED_TIPS, '', '删除失败');
            return formatData('', 200, CodeData::NEED_TIPS, '相片不存在');
        }
    }


    /**
     * Note - 获取照片列表
     * DateTime 2024/8/9 16:15
     * User Admin
     * @param $uid
     * @return array
     */
    public function view($uid)
    {
        $memcache = MemcacheClient::getInstance();
        $photos = $memcache->get('user_photo_' . $uid);
        if ($photos === false) {
            $photos = Photo::query()->where('uid', $uid)->orderBy('ctime', 'desc')->get()->toArray();
            if (!empty($photos)) {
                foreach ($photos as $key => $photo) {
                    $photos[$key]['path'] = FunUtil::formatPhoto($photo['path']);
                    $photos[$key]['thumb'] = FunUtil::formatPhoto($photo['thumb']);
                }
            } else {
                $photos = array();
            }
            // $memcache->set('user_photo_' . $uid, $photos, MEM_TIME);
        }
        // Tool::JSON(\CodeData::SUCCESS, array('result' => 1, 'msg' => $photos, 'reward' => '', 'limit_count' => 30), '加载成功');
        return formatData(['result' => 1, 'msg' => $photos, 'reward' => '', 'limit_count' => 30], 200, CodeData::SUCCESS, '加载成功');
    }


}